import 'dart:convert';
import 'dart:developer';
import 'package:dio/dio.dart';

List<String> _imageUri = <String>[];
class GetImageUri{
  static int i = 0;
  Future<List<String>> getImageUri(int num) async{
    return _getData0(num);
  }

  Future<List<String>> _getData0(int num) async{
    Dio dio = Dio();
    _imageUri.clear();
    for(int i = 0; i < num; i++){
      Response response = await dio.get("http://api.mtyqx.cn/tapi/random.php?return=json");
      try {
        Map<String,dynamic> value = JsonDecoder().convert(response.toString());
        if(value != null && value.containsKey("imgurl")){
          _imageUri.add(value["imgurl"]);
        }
      } on FormatException catch (e){
        log(e.message);
        _getData0(1);
      } on DioError catch(e){

      }

    }
    dio.close();
    return _imageUri;
  }

//备用接口
  Future<List<String>> _getData1(int num) async{
    Dio dio = Dio();
    _imageUri.clear();
    for(int i = 0; i < num; i++){
      Response response = await dio.get("https://bing.ioliu.cn/v1/rand?type=json");
      try{
        Map<String,dynamic> value = JsonDecoder().convert(response.toString());
        if(value != null && value.containsKey("data")){
          _imageUri.add(value["data"]["url"]);
        }
      } on FormatException catch (e){
        log(e.message);
        _getData1(1);
      }

    }
    dio.close();
    return _imageUri;
  }

  //备用接口2
  Future<List<String>> _getData2(int num) async{
    Dio dio = Dio();
    _imageUri.clear();
    for(int i = 0; i < num; i++){
      Response response = await dio.get("http://api.mtyqx.cn/tapi/random.php?return=json");
      try{
        Map<String,dynamic> value = JsonDecoder().convert(response.toString());
        if(value != null && value.containsKey("imgurl")){
          _imageUri.add(value["imgurl"]);
        }
      } on FormatException catch (e){
        log(e.message);
        _getData2(1);
      }
    }
    dio.close();
    return _imageUri;
  }

}